package com.cpointerz.jgtd.helper;

import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

@Component
public class FileHelper {
    public static final String ROOT_DIR = "/data/workspace/jgtd/fileserver/serverRoot/nots";
    public static final String SERVER_ROOT = "http://192.168.0.41:10002/";

    public String saveContent(String content, Integer id) {
        BufferedWriter bw = null;
        try {
            File mdFileDir = new File(ROOT_DIR, id.toString());
            mdFileDir.mkdir();
            File mdFile = new File(mdFileDir, "main.md");
            bw = new BufferedWriter(new FileWriter(mdFile));
            bw.write(content);
            return SERVER_ROOT + id.toString() + "/main.md";
        } catch (Exception e) {
            // 把异常打包为RuntimeException,并在ReturnAspect统一处理
            throw new RuntimeException(e);
        } finally {
            // 如果在bw实例化之前抛出异常，直接关闭会导致NPE,所以在关闭前判空
            if (bw != null) {
                try {
                    bw.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
